<template>
  <div class="app-container bg-white">
    <div class="hor mg-b-10">
      <!--      <el-input-->
      <!--        style="width: 200px"-->
      <!--        class="mg-l-10"-->
      <!--        placeholder="请输入名称"-->
      <!--        v-model="searchName"-->
      <!--        @clear="onInputClear(1)"-->
      <!--        clearable>-->
      <!--      </el-input>-->
      <el-button type="primary" icon="el-icon-search" @click="onClickSearch()" class="mg-l-20">刷新
      </el-button>
      <div class="flex1"></div>
      <el-button type="primary" icon="el-icon-plus" class="mg-l-10"
                 @click="onClickAdd()"></el-button>

      <!--      <el-button-group class="mg-l-10">-->
      <!--        <el-tooltip class="item" effect="dark" content="删除后无法恢复" placement="bottom">-->
      <!--          <el-button type="danger" @click="onDeleteDialogShow = true">删除</el-button>-->
      <!--        </el-tooltip>-->

      <!--      </el-button-group>-->
    </div>
    <div class="ver bg-shadow-gray10 border-gray corner15 pd-tb25 pd-lr25 bg-white"
         style="overflow-y: scroll"
         :style="{height:autoHeight}">
      <el-tree
        class=""
        :data="allList"
        :props="defaultProps"
        node-key="id"
        draggable
        default-expand-all
        @node-drop="onDragEnd"
        :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            class="mg-l-10"
            type="text"
            size="mini"
            @click="() => onClickView(data)">
            详情
          </el-button>
          <el-button
            class="mg-l-10"
            type="text"
            v-if="data.level == 1"
            size="mini"
            @click="() => onClickAddNode(data)">
            新增子公司
          </el-button>
          <!--         <el-button-->
          <!--           class="mg-l-10"-->
          <!--           type="text"-->
          <!--           size="mini"-->
          <!--           @click="() => onClickRemove(node, data)">-->
          <!--              删除-->
          <!--         </el-button>-->
          <el-popconfirm
            class="mg-l-10"
            title="是否确认删除？"
            icon="el-icon-info"
            iconColor="red"
            confirmButtonText='删除'
            @confirm=" onClickRemove(node, data)">
            <el-button slot="reference" type="text" size="mini">删除</el-button>
          </el-popconfirm>
        </span>
      </span>
      </el-tree>
    </div>

    <el-dialog
      title="信息"
      :visible.sync="infoDialogShow"
      width="400px"
      @open="onDialogOpen"
      center>
      <div class="ver match-width">
        <el-form label-width="130px">
          <el-form-item :label="detail.level==1?'区域公司名称':'城市公司名称'">
            <el-input v-model="detail.name" style="width: 200px;"/>
          </el-form-item>
          <el-form-item label="省市" v-if="detail.level!=1">
            <el-cascader
              class=""
              v-model="detail.city"
              placeholder="请选择省市"
              :options="regionList"
              @change="onRegionChange"
              :props="{ expandTrigger: 'hover' }"
              clearable></el-cascader>
          </el-form-item>
          <el-form-item label="公司描述">
            <el-input v-model="detail.des" style="width: 200px;" maxlength="500" show-word-limit
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 8}"/>
          </el-form-item>
        </el-form>

        <div class="hor match-width ver-center hor-center mg-t-20">
          <el-button @click="infoDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="onClickSave" :loading="onSaveLoading">确 定</el-button>
        </div>

      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="onDeleteDialogShow"
      width="30%">
      <span>删除后无法恢复</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onDeleteDialogShow = false">取消</el-button>
        <el-button type="danger" @click="batchDelete()" :loading="onDeleteLoading">删除</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<style>
</style>
<script>
  const request = require('@/api/project/company')
  import {getCityData} from '@/js/cityData.js'

  let _this
  export default {
    filters: {
      // statusFilter(status) {
      //   const statusMap = {
      //     published: 'success',
      //     draft: 'gray',
      //     deleted: 'danger'
      //   }
      //   return statusMap[status]
      // }
    },
    data() {
      return {
        allList: null,
        allAccess: null,
        page: 1,
        size: 20,
        total: 0,
        autoHeight: 800,//根据屏幕高度自动计算的高度
        //筛选参数
        params: {},
        searchName: '',
        selectRowList: [],
        onDeleteDialogShow: false,
        onDeleteLoading: false,

        //信息窗口
        infoDialogShow: false,
        detail: {
          parent: {}
        },
        onSaveLoading: false,
        regionList: [],

        listLoading: true,
        listLoading2: true,

        ///
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      }
    }, beforeMount() {
      _this = this
      this.authHeight = (document.body.scrollHeight - 140) + "px";

      this.regionList = getCityData()
      //去掉第三级的信息
      for (let i = 0; i < this.regionList.length; i++) {
        if (this.regionList[i].children != null && this.regionList[i].children.length > 0) {
          for (let j = 0; j < this.regionList[i].children.length; j++) {
            this.regionList[i].children[j].children = null
          }
        }
      }
    }, mounted() {
      this.fetchData()
    },
    created() {

    },
    methods: {
      fetchData() {
        this.listLoading = true
        const data = new FormData()
        for (var key in this.params) {//直接去除掉空值的对象
          if (this.isEmpty(this.params[key])) {
            delete this.params[key]
          }
        }
        this.params['level'] = 1
        this.params['flag'] = 1
        this.size = 9999
        console.log(this.params)
        data.append('params', JSON.stringify(this.params))
        data.append('page', this.page)
        data.append('size', this.size)
        const sortList = []
        sortList.push(
          {
            direction: 'asc',
            property: 'sort'
          }
        )
        data.append('sortJsonStr', JSON.stringify(sortList))

        request.getList(data).then(response => {
          this.allList = response.data
          this.total = response.totalElements

          this.listLoading = false
        })
      }, saveOrganization() {
        this.onSaveLoading = true
        if (this.isEmpty(this.detail.parent.id)) {
          this.detail.parent = null
        }
        const data = new FormData()
        data.append('json', JSON.stringify(this.detail))
        request.saveByJson(data).then(response => {
          this.onSaveLoading = false
          this.infoDialogShow = false
          this.$message({
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        }).catch((e) => {
          this.onSaveLoading = false
        })
      }, onClickSearch() {//点击搜索
        if (!this.isEmpty(this.searchName)) {
          this.params['name_like'] = ('%' + this.searchName.trim() + '%')
        } else {
          this.params['name_like'] = ''
        }

        this.fetchData()
      }, onClickAddNode(data) {
        if (!this.isHadPermission(['businessDirOperateAccess'])) {
          this.noPermissionHint()
          return
        }

        console.log(data)
        this.detail = {
          parent: {
            id: data.id
          }
        }
        this.infoDialogShow = true
      }, onClickRemove(node, data) {
        if (!this.isHadPermission(['businessDirOperateAccess'])) {
          this.noPermissionHint()
          return
        }

        console.log(node)
        console.log(data)

        const array = [data.id]
        const p = new FormData()
        p.append('ids', array)

        this.$message({
          message: '操作中',
          type: 'warning',
          duration: 1000
        })
        this.onDeleteLoading = true
        request.deletesByLogic(p).then(response => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 3000
          })
          this.onDeleteLoading = false
          this.onDeleteDialogShow = false
          _this.fetchData()
        }).catch((e) => {
          this.onDeleteLoading = false
        })
      }
      , onClickAdd() {
        // if (!this.isHadPermission(['businessDirOperateAccess'])) {
        //   this.noPermissionHint()
        //   return
        // }

        this.detail = {
          level: 1,
          parent: {}
        }
        this.infoDialogShow = true
      }, onDialogOpen() {
      }, onAccessChange(val) {
        this.selectAccess = val
        console.log(this.selectAccess)
      }, onClickSave() {//点击保存
        if (this.isEmpty(this.detail.name)) {
          this.$message({
            message: '请填写名称',
            type: 'warning',
            duration: 2000
          })
          return
        }
        this.saveOrganization()
      }, onClickView(row) {
        if (row.parent == null) {
          row.parent = {}
        }
        this.detail = row
        this.infoDialogShow = true

      }, onDragEnd(beforeNode, afterNode, type, event) {
        console.log(beforeNode.key + "   " + beforeNode.label)
        console.log(afterNode.key + "   " + afterNode.label)
        console.log(type)

        this.loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })

        const p = new FormData()
        p.append('originId', beforeNode.key)
        p.append('relId', afterNode.key)
        p.append('type', type)

        request.updateSort(p).then(response => {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 3000
          })
          this.loading.close()
        }).catch((e) => {
          this.loading.close()
        })
      }, onRegionChange(val) {
        const one = val[0]
        const two = val[1]

        this.detail.province = one;
        this.detail.city = two;

        this.requestDesignProjectList()
      }
    }
  }
</script>
